package com.zzk.audiovideodemo.textureView;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.zzk.audiovideodemo.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @ProjectName: AudioVideoDemo ，使用Camera1
 * @Package: com.zzk.audiovideodemo.textureView
 * @ClassName: TextureViewCamera2Activity
 * @Description:
 * @Author: brilliantzhao
 * @CreateDate: 2021.3.20 15:57
 * @UpdateUser:
 * @UpdateDate: 2021.3.20 15:57
 * @UpdateRemark:
 * @Version: 1.0.0
 */
public class TextureViewCamera1ComplexActivity extends AppCompatActivity implements View.OnClickListener {

    private CameraPreview mPreview;
    private FrameLayout fl_camera_preview;
    private ImageView takePhone;
    private ImageView flash_button;
    //是否开启闪光灯
    private boolean isFlashing;

    //图片临时缓存
    private byte[] imageData;

    private ImageView save_button;
    private ImageView cancle_save_button;
    private Button cancle_button;

    private RelativeLayout ll_photo_layout;
    private RelativeLayout ll_confirm_layout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //在相机界面设置全屏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        // 以上两句代码在setContentView之前执行。
        setContentView(R.layout.activity_textureview_camera1_complex);

        fl_camera_preview = findViewById(R.id.camera_preview);
        takePhone = findViewById(R.id.take_photo_button);
        takePhone.setOnClickListener(this);
        flash_button = findViewById(R.id.flash_button);
        flash_button.setOnClickListener(this);
        ll_photo_layout = findViewById(R.id.ll_photo_layout);
        ll_confirm_layout = findViewById(R.id.ll_confirm_layout);
        save_button = findViewById(R.id.save_button);
        save_button.setOnClickListener(this);
        cancle_save_button = findViewById(R.id.cancle_save_button);
        cancle_save_button.setOnClickListener(this);
        cancle_button = findViewById(R.id.cancle_button);
        cancle_button.setOnClickListener(this);

        //  初始化预览界面，并设置监听
        // 创建预览界面
        mPreview = new CameraPreview(this);
        //设置透明度
        mPreview.setAlpha(1f);

        //将预览页面添加到FrameLayout中
        fl_camera_preview.addView(mPreview);
        //设置监听
        mPreview.setSurfaceTextureListener(mPreview);
    }

    /**
     * 调用摄像头开始拍照片
     */
    private void takePhoto() {
        //调用相机拍照
        final Camera mCamera = mPreview.getCamera();
        if (mCamera == null) {
            return;
        }
        //拍照
        mCamera.takePicture(null, null, null, new Camera.PictureCallback() {
            @Override
            public void onPictureTaken(byte[] data, Camera camera) {
                //视图动画
                ll_photo_layout.setVisibility(View.GONE);

                ObjectAnimator anim1 = ObjectAnimator.ofFloat(ll_confirm_layout, "scaleX", 0, 1.0f);
                ObjectAnimator anim2 = ObjectAnimator.ofFloat(ll_confirm_layout, "scaleY", 0, 1.0f);

                AnimatorSet animatorSet = new AnimatorSet();
                animatorSet.setDuration(1000);
                animatorSet.play(anim1).with(anim2);
                animatorSet.setInterpolator(new AccelerateDecelerateInterpolator());
                animatorSet.start();

                ll_confirm_layout.setVisibility(View.VISIBLE);

                //停止预览
                mCamera.stopPreview();

                imageData = data;
            }
        });
    }

    /**
     * 保存照片
     *
     * @param imageData
     */
    private void savePhoto(byte[] imageData) {
        if (imageData.length == 0) {
            return;
        }
        FileOutputStream fos = null;
        String cameraPath = Environment.getExternalStorageDirectory().getPath() + File.separator + "1";
        //相册文件夹
        File cameraFolder = new File(cameraPath);
        if (!cameraFolder.exists()) {
            cameraFolder.mkdirs();
        }
        //保存的图片文件
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
        String imagePath = cameraFolder.getAbsolutePath() + File.separator + "IMG_" + simpleDateFormat.format(new Date()) + ".jpg";
        File imageFile = new File(imagePath);
        try {
            fos = new FileOutputStream(imageFile);
            fos.write(imageData);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 切换闪光灯
     */
    private void switchFlash() {
        Camera mCamera = mPreview.getCamera();
        if (mCamera == null) {
            return;
        }
        isFlashing = !isFlashing;
        flash_button.setImageResource(isFlashing ? R.mipmap.flash_open : R.mipmap.flash_close);
        try {
            Camera.Parameters parameters = mCamera.getParameters();
            parameters.setFlashMode(isFlashing ? Camera.Parameters.FLASH_MODE_TORCH : Camera.Parameters.FLASH_MODE_OFF);
            mCamera.setParameters(parameters);
        } catch (Exception e) {
            Toast.makeText(this, "该设备不支持闪光灯", Toast.LENGTH_SHORT);
        }
    }

    /**
     * 快速切换到预览状态
     */
    private void changePreview() {
        Camera mCamera = mPreview.getCamera();
        if (mCamera == null) {
            return;
        }
        ll_confirm_layout.setVisibility(View.GONE);

        ObjectAnimator anim1 = ObjectAnimator.ofFloat(ll_photo_layout, "scaleX", 0, 1.0f);
        ObjectAnimator anim2 = ObjectAnimator.ofFloat(ll_photo_layout, "scaleY", 0, 1.0f);

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.setDuration(1000);
        animatorSet.play(anim1).with(anim2);
        animatorSet.setInterpolator(new AccelerateDecelerateInterpolator());
        animatorSet.start();

        ll_photo_layout.setVisibility(View.VISIBLE);

        //开始预览
        mCamera.startPreview();
        imageData = null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.take_photo_button:
                //拍照
                takePhoto();
                break;
            case R.id.flash_button:
                //切换闪光灯
                switchFlash();
                break;
            case R.id.save_button:
                //保存照片
                savePhoto(imageData);
                //切换到预览状态
                changePreview();
                break;
            case R.id.cancle_save_button:
                //切换到预览状态
                changePreview();
                break;
            case R.id.cancle_button:
                finish();
                break;
        }
    }
}